package com.liuchuanzheng.lcz_compose_news.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.liuchuanzheng.lcz_compose_news.ext.State
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

/**
 * @author 刘传政
 * @date 2021/8/2 11:14
 * QQ:1052374416
 * 电话:18501231486
 * 作用:
 * 注意事项:
 */
open class BaseViewModel : ViewModel() {
    val stateLiveData = MutableLiveData<State>().apply {
        value = State.Loading
    }

    fun launch(block: suspend CoroutineScope.() -> Unit) {
        viewModelScope.launch {
            try {
                block()
                stateLiveData.value = State.Success
            }catch (e: Exception) {
                stateLiveData.value = State.Error(e.message)
            }
        }
    }
}